package main

import (
	"github.com/op/go-logging"
	"os"
)

type MultipleBackEndLogger struct {
	logging.Logger
	BackEnds []*BackEndItem
}

type BackEndItem struct {
	ID string
	BackEnd logging.Backend
}

func NewMultipleBackEndLogger(module string) *MultipleBackEndLogger {
	backend := logging.NewLogBackend(os.Stdout, "", 0)
	ErrBackend := logging.NewLogBackend(os.Stderr, "", 0)
	format := logging.MustStringFormatter(
		`%{time:2006-01-02T15:04:05-0700} ipa2s3 %{color} %{shortfunc} %{level:.4s} %{shortfile} %{id:03x}%{color:reset} %{message}`,
	)
	backendFormatter := logging.NewBackendFormatter(backend, format)
	ErrBackendFormatter := logging.NewBackendFormatter(ErrBackend, format)

	backend1Leveled := logging.AddModuleLevel(backendFormatter)
	backend1Leveled.SetLevel(logging.INFO, "")
	ErrBackend1Leveled := logging.AddModuleLevel(ErrBackendFormatter)
	ErrBackend1Leveled.SetLevel(logging.ERROR, "")


	log2 := MultipleBackEndLogger{
		BackEnds: []*BackEndItem{},
	}
	log2.Module = module

	log2.AddBackEnd(&BackEndItem{
		ID: `info`,
		BackEnd: backend1Leveled,
	}, &BackEndItem{
		ID: `error`,
		BackEnd: ErrBackend1Leveled,
	})

	return &log2
}

func (this *MultipleBackEndLogger) AddBackEnd(backend ...*BackEndItem) {
	this.BackEnds = append(this.BackEnds, backend...)
	list := make([]logging.Backend, 0)
	for _, item := range this.BackEnds {
		list = append(list, item.BackEnd)
	}
	logging.SetBackend(list...)
	//fmt.Println(this.BackEnds)
}

func (this *MultipleBackEndLogger) RemoveBackEnd(backend *BackEndItem) {
	i := -1
	for k, ele := range this.BackEnds {
		if ele.ID == backend.ID {
			i = k
			//fmt.Println(`found removed backend`, i)
			break
		}
	}
	if i > -1 {
		this.BackEnds = append(this.BackEnds[:i], this.BackEnds[i+1:]...)
		list := make([]logging.Backend, 0)
		for _, item := range this.BackEnds {
			list = append(list, item.BackEnd)
		}
		logging.SetBackend(list...)
	}
}